<template>
	<BaseField v-bind="props">
		<div class="field-text">
			<div class="view flex" style="align-items: center; gap: 4px" v-if="status === 'view'">
				<ComIcon v-if="dataValue === trueValue" icon="iconCheck"></ComIcon>
				<ComIcon v-else icon="iconClose"></ComIcon>
				{{ dataValue === trueValue ? $t("fieldType.boolean_obj.yes") : $t("fieldType.boolean_obj.no") }}
			</div>
			<div class="edit" style="width: 100%" v-else>
				<a-switch :size="size" v-model="dataValue" :checked-value="trueValue" :unchecked-value="falseValue" @change="handleUpdate">
					<template #checked-icon>
						<icon-check />
					</template>
					<template #unchecked-icon>
						<icon-close />
					</template>
				</a-switch>
			</div>
		</div>
	</BaseField>
</template>

<script setup lang="ts">
import { propsInfo } from "./utils/props";
import { useI18n } from "@/hooks/useI18n";
import { isValid } from "@/utils";
const { t } = useI18n();
const props = defineProps(propsInfo);
const emit = defineEmits(["update:modelValue", "update:fieldShow", "change"]);
const dataValue: any = ref([]);

const handleUpdate = (data) => {
	emit("update:modelValue", dataValue.value);
	emit("update:fieldShow", dataValue.value === trueValue.value ? t("fieldType.boolean_obj.yes") : t("fieldType.boolean_obj.no"));
	if (data) {
		emit("change", dataValue.value);
	}
};

const trueValue = computed(() => {
	const obj = props.arcoProps;
	const val = obj["checked-value"];
	return val === undefined ? true : val;
});
const falseValue = computed(() => {
	const obj = props.arcoProps;
	const val = obj["unchecked-value"];
	return val === undefined ? false : val;
});
watch(
	() => props.modelValue,
	(data) => {
		dataValue.value = isValid(data) ? (data === trueValue.value ? trueValue.value : falseValue.value) : "";
		handleUpdate(false);
	},
	{ immediate: true }
);
</script>

<style scoped></style>
